package nin.ja;

public class ObjectPool {
	public static final int DEFAULT_SIZE = 32;
	
	private Object[] pool;
	private boolean[] inUse;
	private int size;

	public ObjectPool(){
		size = DEFAULT_SIZE;
		setSize(size);
	}
	
	public ObjectPool(int size){
		this.size = size;
		setSize(size);
	}
	
	public Object allocate(){
		for(int i = inUse.length - 1; i >= 0; --i){
			if(!inUse[i]){
				inUse[i] = true;
				return pool[i];
			}
		}
		return null; // Returns null if no more elements in pool
					 // Need smarter way of handling this...
					 // Throw exception? Wait until resources available?
	}
	
	public void release(Object o){
		for(int i = inUse.length - 1; i >= 0; --i){
			if(pool[i] == o){
				inUse[i] = false;
				return;
			}
		}
		// Code comes here if object being released is not from pool
		// This should never happen. Perhaps put assert statement?
		// This is a major issue; would rather fail-fast than fail-safe
	}
	
	public void setSize(int size){
		this.size = size;
		pool = new Object[size];
		inUse = new boolean[size];
		for(int i = 0; i < size; ++i){
			pool[i] = new Object();
			inUse[i] = false;
		}
	}
	
	public int getSize(){
		return size;
	}
}
